package com.hjq.aop;

import com.hjq.mapper.OperateLogMapper;
import com.hjq.pojo.OperateLog;
import com.hjq.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 日志操作切面类
 */
@Component
@Aspect
@Slf4j
public class OperationLogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.hjq.anno.LogOperation)")
    public Object logOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();

        // 执行方法
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        // 计算方法执行耗时
        long costTime = end - start;

        //记录操作日志
        OperateLog operateLog = new OperateLog();
        // 获取当前操作用户id
        operateLog.setOperateEmpId(CurrentHolder.getCurrentId());
        operateLog.setOperateTime(LocalDateTime.now());
        // 获取目标类名
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        // 获取目标方法名
        operateLog.setMethodName(joinPoint.getSignature().getName());
        // 获取目标方法参数
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        // 获取目标方法返回值
        operateLog.setReturnValue(result!=null ? result.toString() : "void");
        // 获取方法执行耗时事件
        operateLog.setCostTime(costTime);

        // 调用mapper方法
        log.info("记录操作日志：{}",operateLog);
        operateLogMapper.insert(operateLog);
        return  result;
    }


}
